#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    : user.py
@Author  : different && 道阻且长,行则将至 行而不辍,未来可期
@Time    : 2021/8/31 10:28
@Desc    : user模型

"""
from flask_login import UserMixin
from sqlalchemy import func
from werkzeug.security import check_password_hash, generate_password_hash

from apps import login_manager
from apps.models.association import user_table
from expand import db


class User(UserMixin, db.Model):
    __tablename__ = 'auth_user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    nickname = db.Column(db.String(20), comment='用户')
    username = db.Column(db.String(20), comment='用户名')
    password_hash = db.Column(db.String(128), comment='密码哈希')
    is_superuser = db.Column(db.Boolean, default=False, nullable=False, comment='是否为超级用户')
    create_time = db.Column(db.DateTime(timezone=True), server_default=func.now(), comment='创建时间')
    tables = db.relationship('DataSourceTitle', secondary=user_table, back_populates="users", cascade='all')

    def __repr__(self):
        return f"User('{self.username}','{self.email}','{self.password}')"

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def validate_password(self, password):
        return check_password_hash(self.password_hash, password)


@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))
